<template>
  <div class="work-order-detail page-container">
    <div class="page-header">
      <h2>工单详情</h2>
      <div>
        <el-button @click="$router.back()">返回</el-button>
        <el-button type="primary" @click="editWorkOrder">编辑</el-button>
      </div>
    </div>

    <el-row :gutter="20" v-loading="loading">
      <el-col :span="16">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>基本信息</span>
              <el-tag :type="getStatusType(workOrder.status)">
                {{ getStatusText(workOrder.status) }}
              </el-tag>
            </div>
          </template>
          
          <el-descriptions :column="2" border>
            <el-descriptions-item label="工单号">{{ workOrder.id }}</el-descriptions-item>
            <el-descriptions-item label="类型">{{ getTypeText(workOrder.type) }}</el-descriptions-item>
            <el-descriptions-item label="优先级">
              <el-tag :type="getPriorityType(workOrder.priority)">
                {{ getPriorityText(workOrder.priority) }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="负责人">{{ workOrder.assignee_name || '未分配' }}</el-descriptions-item>
            <el-descriptions-item label="创建人">{{ workOrder.creator_name || '未知' }}</el-descriptions-item>
            <el-descriptions-item label="创建时间">{{ formatDate(workOrder.created_at) }}</el-descriptions-item>
            <el-descriptions-item label="区域">{{ workOrder.area_name || '未指定' }}</el-descriptions-item>
            <el-descriptions-item label="备注" :span="2">{{ workOrder.notes || '无' }}</el-descriptions-item>
          </el-descriptions>
          
          <!-- 自定义字段 -->
          <div v-if="customFieldValues && Object.keys(customFieldValues).length > 0" style="margin-top: 20px;">
            <el-divider content-position="left">自定义字段</el-divider>
            <el-descriptions :column="2" border>
              <el-descriptions-item 
                v-for="(value, fieldName) in customFieldValues" 
                :key="fieldName"
                :label="getCustomFieldLabel(fieldName)"
              >
                <span v-if="Array.isArray(value)">{{ value.join(', ') }}</span>
                <span v-else-if="typeof value === 'string' && (value.startsWith('[') || value.includes(','))">{{ formatArrayValue(value) }}</span>
                <span v-else>{{ value || '无' }}</span>
              </el-descriptions-item>
            </el-descriptions>
          </div>
        </el-card>

        <el-card style="margin-top: 20px;">
          <template #header>
            <span>处理记录</span>
          </template>
          
          <el-timeline>
            <el-timeline-item
              v-for="record in processRecords"
              :key="record.id"
              :timestamp="formatDate(record.created_at)"
              placement="top"
            >
              <el-card>
                <h4>{{ record.action }}</h4>
                <p>{{ record.description }}</p>
                <p class="operator">操作人：{{ record.operator }}</p>
              </el-card>
            </el-timeline-item>
          </el-timeline>
        </el-card>
      </el-col>

      <el-col :span="8">
        <el-card>
          <template #header>
            <span>状态操作</span>
          </template>
          
          <div class="status-actions">
            <el-row :gutter="10">
              <el-col :span="8" v-if="workOrder.status === 'pending'">
                <el-button
                  type="primary"
                  @click="updateStatus('in_progress')"
                  style="width: 100%;"
                >
                  开始处理
                </el-button>
              </el-col>
              <el-col :span="8" v-if="workOrder.status === 'in_progress'">
                <el-button
                  type="success"
                  @click="updateStatus('completed')"
                  style="width: 100%;"
                >
                  完成工单
                </el-button>
              </el-col>
              <el-col :span="8" v-if="workOrder.status !== 'completed'">
                <el-button
                  type="warning"
                  @click="updateStatus('pending')"
                  style="width: 100%;"
                >
                  重置为待处理
                </el-button>
              </el-col>
              <el-col :span="8">
                <el-button
                  type="info"
                  @click="openMaterialDialog"
                  style="width: 100%;"
                >
                  材料录入
                </el-button>
              </el-col>
            </el-row>
          </div>
        </el-card>

        <el-card style="margin-top: 20px;">
          <template #header>
            <span>添加处理记录</span>
          </template>
          
          <el-form @submit.prevent="addRecord">
            <el-form-item>
              <el-input
                v-model="newRecord.description"
                type="textarea"
                :rows="4"
                placeholder="请输入处理记录..."
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="addRecord">添加记录</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>
    </el-row>

    <!-- 材料录入对话框 -->
    <el-dialog
      v-model="showMaterialDialog"
      title="材料录入"
      width="800px"
      :before-close="handleMaterialDialogClose"
    >
      <!-- 材料选择区域 -->
      <el-card class="material-select-card" style="margin-bottom: 20px;">
        <template #header>
          <span>选择材料</span>
        </template>
        <el-form :model="materialForm" label-width="100px">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="材料" prop="material_id">
                <el-select
                  v-model="materialForm.material_id"
                  placeholder="请选择材料"
                  filterable
                  style="width: 100%"
                  @change="onMaterialSelect"
                >
                  <el-option
                    v-for="material in availableMaterials"
                    :key="material.id"
                    :label="`${material.name} (${material.code})`"
                    :value="material.id"
                  >
                    <div style="display: flex; justify-content: space-between;">
                      <span>{{ material.name }}</span>
                      <span style="color: #999; font-size: 12px;">库存: {{ material.stock_quantity }} {{ material.unit }}</span>
                    </div>
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="使用数量" prop="quantity">
                <el-input-number
                  v-model="materialForm.quantity"
                  :min="1"
                  :max="selectedMaterial?.stock_quantity || 999999"
                  placeholder="请输入数量"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
          </el-row>
          
          <div style="text-align: right; margin-top: 10px;">
            <el-button type="primary" @click="addMaterialToList" :disabled="!materialForm.material_id || !materialForm.quantity">添加至清单</el-button>
          </div>
        </el-form>
      </el-card>

      <!-- 已录入材料列表 -->
      <el-card class="used-materials-card" style="margin-bottom: 20px;">
        <template #header>
          <span>已录入材料</span>
        </template>
        <el-table :data="usedMaterials" stripe style="width: 100%" empty-text="暂无已录入材料" show-summary :summary-method="getSummaries">
          <el-table-column prop="material_name" label="材料名称" />
          <el-table-column prop="material_specification" label="规格型号" />
          <el-table-column prop="quantity" label="使用数量">
            <template #default="{ row }">
              {{ row.quantity }} {{ row.material_unit }}
            </template>
          </el-table-column>
          <el-table-column prop="unit_price" label="单价">
            <template #default="{ row }">
              ￥{{ row.unit_price ? row.unit_price.toFixed(2) : '0.00' }}
            </template>
          </el-table-column>
          <el-table-column prop="total_price" label="总价">
            <template #default="{ row }">
              ￥{{ row.total_price ? row.total_price.toFixed(2) : '0.00' }}
            </template>
          </el-table-column>
          <el-table-column prop="user_name" label="使用人" />
          <el-table-column prop="usage_date" label="使用日期">
            <template #default="{ row }">
              {{ formatDate(row.usage_date) }}
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template #default="{ row }">
              <el-button
                text
                type="danger"
                size="small"
                @click="deleteUsedMaterial(row.usage_id)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>

      <!-- 待添加材料列表 -->
      <el-card class="materials-to-add-card">
        <template #header>
          <span>待录入材料清单</span>
        </template>
        <el-table :data="materialsToAdd" style="width: 100%" empty-text="暂无待录入材料">
          <el-table-column prop="name" label="材料名称" />
          <el-table-column prop="specification" label="规格型号" />
          <el-table-column prop="quantity" label="使用数量" width="120">
            <template #default="{ row }">
              {{ row.quantity }} {{ row.unit }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="80">
            <template #default="{ $index }">
              <el-button type="danger" size="small" @click="removeMaterialFromList($index)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleMaterialDialogClose">取消</el-button>
          <el-button type="primary" @click="submitMaterialUsage" :disabled="materialsToAdd.length === 0">确定录入</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { workOrdersApi } from '@/api'
import { materialsApi } from '@/api'

const route = useRoute()
const router = useRouter()
const loading = ref(false)

// 自定义字段相关数据
const customFields = ref([])
const customFieldValues = ref({})

const workOrder = ref({})

const processRecords = ref([])

const newRecord = reactive({
  description: ''
})

// 材料录入相关数据
const showMaterialDialog = ref(false)
const availableMaterials = ref([])
const selectedMaterial = ref(null)
const materialsToAdd = ref([])
const usedMaterials = ref([])
const materialForm = reactive({
  material_id: '',
  quantity: 1
})

const getStatusType = (status: string) => {
  const types: Record<string, string> = {
    pending: 'warning',
    assigned: 'info',
    in_progress: 'primary',
    completed: 'success',
    cancelled: 'danger'
  }
  return types[status] || 'info'
}

const getStatusText = (status: string) => {
  const texts: Record<string, string> = {
    pending: '待处理',
    assigned: '已分配',
    in_progress: '处理中',
    completed: '已完成',
    cancelled: '已取消'
  }
  return texts[status] || status
}

const getPriorityType = (priority: string) => {
  const types: Record<string, string> = {
    low: 'info',
    medium: 'warning',
    high: 'danger'
  }
  return types[priority] || 'info'
}

const getPriorityText = (priority: string) => {
  const texts: Record<string, string> = {
    low: '低',
    medium: '中',
    high: '高'
  }
  return texts[priority] || priority
}

const getTypeText = (type: string) => {
  const texts: Record<string, string> = {
    maintenance: '维修',
    cleaning: '清洁',
    safety: '安全检查',
    other: '其他'
  }
  return texts[type] || type
}

// 获取自定义字段标签
const getCustomFieldLabel = (fieldName: string) => {
  const field = customFields.value.find(f => f.name === fieldName)
  return field ? field.label : fieldName
}

// 格式化数组值
const formatArrayValue = (value: string) => {
  try {
    // 尝试解析JSON数组
    if (value.startsWith('[') && value.endsWith(']')) {
      const parsed = JSON.parse(value)
      return Array.isArray(parsed) ? parsed.join(', ') : value
    }
    // 处理逗号分隔的字符串
    if (value.includes(',')) {
      return value.split(',').map(item => item.trim()).join(', ')
    }
    return value
  } catch (error) {
    // 如果解析失败，返回原值
    return value
  }
}

// 格式化日期为 yyyy/mm/dd 格式
const formatDate = (dateString: string) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  if (isNaN(date.getTime())) return dateString
  
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  
  return `${year}/${month}/${day}`
}

// 加载自定义字段
const loadCustomFields = async () => {
  try {
    const response = await workOrdersApi.getCustomFields()
    customFields.value = response.data.fields
  } catch (error) {
    console.error('加载自定义字段失败:', error)
  }
}

// 加载处理记录
const loadProcessRecords = async () => {
  try {
    const id = route.params.id
    const response = await workOrdersApi.getProcessRecords(id)
    processRecords.value = response.data.process_records || []
  } catch (error) {
    console.error('加载处理记录失败:', error)
    ElMessage.error('加载处理记录失败')
  }
}

const loadWorkOrder = async () => {
  loading.value = true
  try {
    const id = route.params.id
    const response = await workOrdersApi.getWorkOrder(id)
    workOrder.value = response.data.work_order
    
    // 处理自定义字段数据
    const customFields = response.data.work_order.custom_fields || {}
    const processedCustomFields = {}
    
    // 将API返回的custom_fields格式转换为组件期望的格式
    Object.keys(customFields).forEach(fieldName => {
      const fieldData = customFields[fieldName]
      processedCustomFields[fieldName] = fieldData.value
    })
    
    customFieldValues.value = processedCustomFields
  } catch (error) {
    console.error('加载工单详情失败:', error)
    ElMessage.error('加载工单详情失败')
  } finally {
    loading.value = false
  }
}

const updateStatus = async (status: string) => {
  try {
    const id = route.params.id
    await workOrdersApi.updateWorkOrder(id, { status })
    
    workOrder.value.status = status
    ElMessage.success('状态更新成功')
    
    // 重新加载工单详情和处理记录
    await loadWorkOrder()
    await loadProcessRecords()
  } catch (error) {
    console.error('状态更新失败:', error)
    ElMessage.error('状态更新失败')
  }
}

const addRecord = async () => {
  if (!newRecord.description.trim()) {
    ElMessage.warning('请输入处理记录')
    return
  }

  try {
    const id = route.params.id
    await workOrdersApi.createProcessRecord(id, {
      description: newRecord.description,
      action: '处理记录'
    })
    
    ElMessage.success('记录添加成功')
    newRecord.description = ''
    
    // 重新加载处理记录
    await loadProcessRecords()
  } catch (error) {
    console.error('添加记录失败:', error)
    ElMessage.error('添加记录失败')
  }
}

const editWorkOrder = () => {
  router.push(`/work-orders/${workOrder.value.id}/edit`)
}

// 材料录入相关方法
const loadAvailableMaterials = async () => {
  try {
    const response = await materialsApi.getMaterials()
    availableMaterials.value = response.data.materials || []
  } catch (error) {
    console.error('加载材料列表失败:', error)
    ElMessage.error('加载材料列表失败')
  }
}

const onMaterialSelect = (materialId) => {
  selectedMaterial.value = availableMaterials.value.find(m => m.id === materialId) || null
  if (selectedMaterial.value) {
    if (selectedMaterial.value.stock_quantity <= 0) {
      ElMessage.warning('该材料库存不足')
    } else if (selectedMaterial.value.stock_quantity < 10) {
      ElMessage.warning('该材料库存较低，请注意补充')
    }
  }
}

const handleMaterialDialogClose = () => {
  showMaterialDialog.value = false
  selectedMaterial.value = null
  materialsToAdd.value = []
  Object.assign(materialForm, {
    material_id: '',
    quantity: 1
  })
}

const addMaterialToList = () => {
  if (!selectedMaterial.value) {
    ElMessage.error('请选择有效的材料')
    return
  }

  if (materialForm.quantity > selectedMaterial.value.stock_quantity) {
    ElMessage.error('使用数量超过库存数量')
    return
  }

  const existingMaterial = materialsToAdd.value.find(m => m.id === selectedMaterial.value.id)
  if (existingMaterial) {
    ElMessage.warning('该材料已在清单中')
    return
  }

  materialsToAdd.value.push({
    ...selectedMaterial.value,
    quantity: materialForm.quantity
  })

  // 重置选择
  selectedMaterial.value = null
  materialForm.material_id = ''
  materialForm.quantity = 1
}

const removeMaterialFromList = (index) => {
  materialsToAdd.value.splice(index, 1)
}

const submitMaterialUsage = async () => {
  if (materialsToAdd.value.length === 0) {
    ElMessage.warning('请至少添加一种材料')
    return
  }

  try {
    const usageData = materialsToAdd.value.map(material => ({
      material_id: material.id,
      quantity: material.quantity,
      work_order_id: workOrder.value.id,
      // user_name 将在后端自动填充
    }))

        await workOrdersApi.addMultipleMaterialUsage(usageData)

    ElMessage.success('材料录入成功')
    handleMaterialDialogClose()

        // 重新加载数据
    await Promise.all([
      loadWorkOrder(),
      loadAvailableMaterials(),
      loadUsedMaterials()
    ])
  } catch (error) {
    console.error('材料录入失败:', error)
    ElMessage.error('材料录入失败')
  }
}

// 计算属性
const loadUsedMaterials = async () => {
  try {
    const id = route.params.id
    const response = await workOrdersApi.getWorkOrderMaterials(id)
    usedMaterials.value = response.data.materials
  } catch (error) {
    console.error('加载已用材料列表失败:', error)
    ElMessage.error('加载已用材料列表失败')
  }
}

const deleteUsedMaterial = async (usageId) => {
  try {
    await workOrdersApi.deleteMaterialUsage(usageId)
    ElMessage.success('删除成功')
    await loadUsedMaterials()
    await loadAvailableMaterials() // 刷新库存
  } catch (error) {
    console.error('删除失败:', error)
    ElMessage.error('删除失败')
  }
}

const getSummaries = (param) => {
  const { columns, data } = param
  const sums = []
  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = '合计'
      return
    }
    if (column.property === 'total_price') {
      const values = data.map(item => Number(item[column.property] || 0))
      const total = values.reduce((prev, curr) => {
        const value = Number(curr)
        return !isNaN(value) ? prev + value : prev
      }, 0)
      sums[index] = `￥${total.toFixed(2)}`
    } else {
      sums[index] = ''
    }
  })
  return sums
}

// 计算属性
const estimatedTotalPrice = computed(() => {
  if (!selectedMaterial.value || !materialForm.quantity) {
    return 0
  }
  return (selectedMaterial.value.unit_price * materialForm.quantity).toFixed(2)
})

const openMaterialDialog = () => {
  showMaterialDialog.value = true
  loadAvailableMaterials()
  loadUsedMaterials()
}

onMounted(() => {
  loadCustomFields()
  loadWorkOrder()
  loadProcessRecords()
  loadAvailableMaterials()
})
</script>

<style scoped>
.work-order-detail {
  width: 100%;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  color: #333;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.status-actions {
  display: flex;
  flex-direction: column;
  gap: 0;
}

.status-actions .el-button {
  width: 100%;
  margin-bottom: 10px;
}

.status-actions .el-button:last-child {
  margin-bottom: 0;
}

.dialog-footer {
  text-align: right;
}

.operator {
  color: #666;
  font-size: 12px;
  margin-top: 5px;
}
</style>
